// pages/goods_detail/goods_detail.js
import {request} from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: {},
    //是否收藏商品
    isCollect: false
  },
  //商品对象
  goodsObj: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {goods_id} = options;
    this.getGoodsDetail(goods_id);
  },

  //获取商品详细数据
  async getGoodsDetail(goods_id) {
    const res = await request({
      url: "/goods/detail",
      data: {goods_id}
    });
    // console.log(res.data.message);
    this.goodsObj = res.data.message;
    this.setData({
      goodsObj: {
        goods_name: this.goodsObj.goods_name,
        goods_price: this.goodsObj.goods_price,
        goods_introduce: this.goodsObj.goods_introduce.replace(/\.webp/g,'.png'),
        goods_id: this.goodsObj.goods_id,
        pics: this.goodsObj.pics
      }
    });
     //收藏
     let collect = wx.getStorageSync("collect")|| [];
     //获取缓存中的收藏数据
     let isCollect = collect.some(v => { 
       return v.goods_id === this.goodsObj.goods_id
      });
      //然后进行设置
      this.setData({
        isCollect
      });
  },
  //点击轮播图放大预览
  PrevewImage(e) {
    const urls = this.goodsObj.pics.map(v=>v.pics_mid),
          {current} = e.currentTarget.dataset;
          // console.log(current);
    wx.previewImage({
      urls,
      current
    })
  },
  //加入购物车
  addCart() {
    //获取缓存中的购物车数组
    let cart = wx.getStorageSync('cart') || [];
    //判断商品对象是否存在于购物车数组中
    let index = cart.findIndex(v=>v.goods_id===this.goodsObj.goods_id);
    //判断是否存在
    if (index === -1) {
      //不存在添加
      this.goodsObj.num = 1;
      this.goodsObj.checked = true;
      cart.push(this.goodsObj);
      // console.log(this.goodsObj.goods_id,index);
    } else {
      //存在加数量
      cart[index].num++;
      console.log('++');
    }
    //把购物车重新添加会缓存
    wx.setStorageSync('cart', cart);
    //弹窗提示
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      mask: true
    })
  },
  //是否收藏
  onCollect() {
    let isCollect = false;
    //获取缓存信息
    let collect = wx.getStorageSync("collect")|| [];
    let index = collect.findIndex(v => v.goods_id === this.goodsObj.goods_id);
    //如果有则删除
    if (index !== -1) {
      collect.splice(index,1);
      isCollect = false;
      this.onPrompt("取消成功");
    } else {
      collect.push(this.goodsObj);
      isCollect = true;
      this.onPrompt("收藏成功");
    }
    wx.setStorageSync('collect', collect);
    this.setData({
      isCollect
    });
  },
  onPrompt(title) {
    wx.showToast({
      title,
      icon: 'success',
      mask: true
    })
  },
  //立即购买
  onBuy() {
    this.addCart();
    wx.switchTab({
      url: '../cart/cart',
    })
  }
})